﻿using System.IO;
using EditRegion.MVC.Editor;
using EditRegion.MVC.Editor.BasicTextArea;
using EditRegion.MVC.Repository;
using EditRegion.MVC.Repository.Xml;

namespace EditRegion.MVC
{
    internal class HtmlServer
    {
        private readonly IContentRepository contentRepository;

        internal HtmlServer()
        {
            contentRepository = new XmlRepository();
        }

        internal HtmlServer(FileSystemInfo fileInfo)
        {
            contentRepository = new XmlRepository(fileInfo);
        }

        internal string GetContent(string regionId)
        {
            return contentRepository.GetById(regionId);
        }

        internal static string GetEditor(string id, string content)
        {
            IHtmlEditor editor = new BasicTextAreaEditor();
            string markUp = editor.GetMarkUp(id, content);
            markUp += GetSaveLinksMarkUp(id);
            return markUp;
        }

        private static string GetSaveLinksMarkUp(string id)
        {
            return "<ul class='editRegionSave'><li><a id=\"save\" href='#' onclick=\"saveEditRegion('" + id + "');\" >save</a><li id=\"result_" + id + "\"></li></ul>";
        }

        internal void SaveContent(string id, string content)
        {
            if(contentRepository.IsExisting(id))
            {
                contentRepository.Update(id, content);
            }
            else
            {
                contentRepository.Add(id, content);
            }
        }
    }
}